/**
 * @param {number} n
 * @param {number[][]} edges[i]
 * @return {number}
 */
var countComponents = function (n, edges) {
  for(let i = 0; i < edges.length; i++) {
    edges[i].sort((a, b) => a - b);
  }
  let visited = new Array(n).fill(false);
  let graph = new Map();

  function DFS(index) {
    visited[index] = true;
    if(graph[index]) {
      for (let i = 0; i < graph[index].length; i++) {
        if(!visited[graph[index][i]])
          DFS(graph[index][i]);
      }
    }

  }
  for (let i = 0; i < edges.length; i++) {
    if (graph[edges[i][0]]) {
      graph[edges[i][0]].push(edges[i][1]);
    } else {
      graph[edges[i][0]] = [edges[i][1]];
    }
    if (graph[edges[i][1]]) {
      graph[edges[i][1]].push(edges[i][0]);
    } else {
      graph[edges[i][1]] = [edges[i][0]];
    }
  }
  let count = 0;
  for (let i = 0; i < n; i++) {
    // 节点没被访问过
    if (!visited[i]) {
      DFS(i);
      count++;
    }
  }
  return count;
};
let n = 5,
  edges = [
    [0, 1],
    [1, 2],
    [3, 4]
  ];
console.log(countComponents(n, edges));
n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]];
console.log(countComponents(n, edges));
n = 4, edges = [[2,3],[1,2],[1,3]];
console.log(countComponents(n, edges));
n = 4, edges = [[0,1],[2,3],[1,2]];
console.log(countComponents(n, edges));
n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[3,5]];
console.log(countComponents(n, edges));
n = 2, edges = [[1, 0]];
console.log(countComponents(n, edges));
